package com.shushan.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.Constants;
import com.shushan.db.ChildBeanDao;
import com.shushan.db.GameTimeDao;
import com.shushan.lockscreen.bean.GameTimeBean;
import com.shushan.login.bean.ChildBean;
import com.shushan.login.bean.UserBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.ToolUtils;

import org.json.JSONArray;

import java.util.List;

/**
 * @ClassName: PostGameTimeServer
 * @Desciption: 上传游戏使用时间服务
 * @author: yichaohua
 * @date: 2018-06-19
 */
public class PostGameTimeServer extends Service {

    private final static String TAG = "PostGameTimeServer";

    private GameTimeDao gameTimeDao;

    @Override
    public void onCreate() {
        super.onCreate();

        gameTimeDao = new GameTimeDao(this);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"onStartCommand()");

        postGameTime();

        return super.onStartCommand(intent, flags, startId);
    }

    private void postGameTime() {
        List<GameTimeBean> gameTimeBeanList = gameTimeDao.queryForAll();
        if(ToolUtils.isListEmpty(gameTimeBeanList)){
            return;
        }

        JSONArray dataArray = new JSONArray();
        for (int i = 0;i < gameTimeBeanList.size();i++){
            GameTimeBean gameTimeBean = gameTimeBeanList.get(i);
            dataArray.put(gameTimeBean.toJSONObject());
        }

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.POST_GAME_TIME);
        urlParse.putValue("childId", BabyApplication.getInstance().getCurrentChildId())
                .putValue("data",dataArray.toString());

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {


                    @Override
                    protected void onSuccess(String data) {
                        gameTimeDao.clearTab();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {

                    }
                });
    }
}
